import click

from app import User, Movie
from app import app, db

# 定义常量
USER_NAME = 'Grey Li'
MOVIES_DATA = [
    {'movie_title': 'My Neighbor Totoro', 'movie_year': '1988'},
    {'movie_title': 'Dead Poets Society', 'movie_year': '1989'},
    {'movie_title': 'A Perfect World', 'movie_year': '1993'},
    {'movie_title': 'Leon', 'movie_year': '1994'},
    {'movie_title': 'Mahjong', 'movie_year': '1996'},
    {'movie_title': 'Swallowtail Butterfly', 'movie_year': '1996'},
    {'movie_title': 'King of Comedy', 'movie_year': '1999'},
    {'movie_title': 'Devils on the Doorstep', 'movie_year': '1999'},
    {'movie_title': 'WALL - E', 'movie_year': '2008'},
    {'movie_title': 'The Pork of Music', 'movie_year': '2012'},
]


def handle_db_operation(func):
    """
    用于处理数据库操作的装饰器，统一异常处理逻辑
    """

    def wrapper():
        try:
            with app.app_context():
                func()
        except Exception as e:
            click.echo(f"Database operation failed: {e}", err=True)
            raise

    return wrapper


# 创建数据库
@handle_db_operation
def create_db():
    """
    清除现有数据并创建新表
    """
    db.drop_all()
    db.create_all()
    click.echo('Initialized the database.')


# 插入数据
@handle_db_operation
def insert_db():
    """
    向数据库插入用户和电影数据
    """
    user = User(username=USER_NAME)
    db.session.add(user)
    for item in MOVIES_DATA:
        movie = Movie(movie_title=item['movie_title'], movie_year=item['movie_year'])
        db.session.add(movie)
    db.session.commit()
    click.echo('Inserted data into the database.')


# 使用 flask 自定义命令
@app.cli.command()
def init_db():
    """
    自定义命令，用于初始化数据库并插入示例数据
    """
    try:
        create_db()
        insert_db()
        click.echo('Database initialized and data inserted successfully.')
    except Exception as e:
        click.echo(f"Failed to initialize the database: {e}", err=True)

if __name__ == '__main__':
    init_db()